<?php


namespace App\Models\CacheModel\privatearea;


use app\common\lib\AliOss;
use App\Models\Api\BaseCache;
use think\Log;
use AstroTool\Cache\CacheManage;

class PrivateAreaQuestionInfo extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.private_area_question_info';

    protected $cacheModel = 'privatearea.user_question';

    /**
     * 更新 用户咨询信息
     * @param int $id
     * @param array $updataData
     * @return bool
     */
    public function updateUserQuestionData(int $id, array $updataData)
    {
        try
        {
            // 更新信息
            $this->where(['id' => $id])->update($updataData);
            // 更新缓存信息
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache($updataData);
            return true;
        }
        catch (\Exception $e)
        {
            Log::write('私域H5 PrivateAreaQuestionInfo model 异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * 获取用户 最新输入信息
     * @param int $uid
     * @param string $hash
     * @return array|null
     * @throws \Exception
     */
    public function getUserQuestionData(int $uid, string $hash): ?array
    {
        $id = $this->where(['uid' => $uid, 'hash' => $hash])->order('id desc')->value('id');
        if ($id)
        {
            return $this->getPrivateAreaQuestionInfo($id);
        } else
        {
            return null;
        }
    }

    /**
     * 缓存获取私域H5 商品信息
     * @param int $id 商品hash
     * @param array $filed
     * @return array
     * @throws \Exception
     */
    public function getPrivateAreaQuestionInfo(int $id, array $filed = [])
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->getDataAndSet(function () use ($id)
        {
            return $this->getPrivateAreaQuestionInfoFromDms($id);
        }, $filed);

        if ($data)
        {
            if (isset($data['question_data']))
            {
                $data['question_data'] = json_decode($data['question_data'], true);
            }

            if (isset($data['supplement_info']))
            {
                $data['supplement_info'] = json_decode($data['supplement_info'], true);
            }

            $data = arrayKeyData2int($data, ['id', 'astro_id', 'uid', 'status', 'create_time', 'pay_time', 'astro_time', 'reply_time', 'last_submit_time', 'success_time']);
        }
        return $data;
    }

    /**
     * 数据库获取私域H5 商品信息
     * @param int $id
     * @return array|mixed
     */
    public function getPrivateAreaQuestionInfoFromDms(int $id)
    {
        try
        {
            $data = $this->where(['id' => $id])->findOrFail()->toArray();
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    /**
     * 咨询信息重组H5展示 数据格式
     * @param array $questionData
     * @param array $goodInfo
     * @param bool $isAdminOrAstr
     * @return array
     */
    public function questionIndeResetShow(array $questionData, array $goodInfo,bool $isAdminOrAstr = false): array
    {
        $resData = [
            [
                'type' => 1,
                'title' => '任务编号',
                'des' => $questionData['id']
            ], [
                'type' => 1,
                'title' => '商品名称',
                'des' => $goodInfo['name']
            ]
        ];
        $sexTxt = [
            1 => '男',
            2 => '女'
        ];
        switch ($goodInfo['type'])
        {
            case 2: // 塔罗
                $resData[] = [
                    'type' => 4,
                    'title' => '塔罗牌',
                    'des' => '用户选择的塔罗牌',
                    'tarot' => json_decode($questionData['question_data']['cards'], true)
                ];
                break;
            case 5: // 骰子
                $dice = (json_decode($questionData['question_data']['divination_data'], true)) ?: [];
                $dice['dice_question'] = $questionData['question_data']['question'];
                $dice['dice_des'] = '用户骰子的结果';
                $resData[] = [
                    'type' => 2,
                    'title' => '占星骰子',
                    'des' => '用户问题',
                    'dice' => $dice
                ];
                break;
            default:
                $aliOss = AliOss::getInstance();
                $recodeInfo = [];
                if ($questionData['question_data']['recode1'])
                {   // 档案1 存在
                    $recode1 = $questionData['question_data']['recode1'];
                    $recodeInfo[] = [
                        'info_type' => 1,
                        'pic' => $recode1['avatar'],
                        'name' => $questionData['question_data']['name1'],
                        'recode_name' => $recode1['name'],
                        'age' => $this->getAgeByBirth($recode1['year'], $recode1['month'], $recode1['day'], 2),
                    ];
                    $recodeInfo[] = [
                        'info_type' => 2,
                        'title' => '档案名称',
                        'des' => $recode1['name'],
                    ];
                    $recodeInfo[] = [
                        'info_type' => 2,
                        'title' => '性别',
                        'des' => $sexTxt[$recode1['type']] ?? '未知',
                    ];
                    $recodeInfo[] = [
                        'info_type' => 2,
                        'title' => '出生时间',
                        'des' => sprintf("%d-%02d-%02d %02d:%02d", $recode1['year'], $recode1['month'], $recode1['day'], $recode1['hour'], $recode1['minute']),
                    ];
                    $recodeInfo[] = [
                        'info_type' => 2,
                        'title' => '出生地点',
                        'des' => "{$recode1['birth_country']}{$recode1['birth_province']}{$recode1['birth_city']}",
                    ];
                    $recodeInfo[] = [
                        'info_type' => 2,
                        'title' => '现居地区',
                        'des' => "{$recode1['live_country']}{$recode1['live_province']}{$recode1['live_city']}",
                    ];
                    if ($questionData['question_data']['photo1'])
                    {
                        $recodeInfo[] = [
                            'info_type' => 3,
                            'pic' => $aliOss->getAuth($questionData['question_data']['photo1']),
                            'name' => '',
                        ];
                    }
                } else
                {   // 档案1不存在
                    if ($questionData['question_data']['name1'])
                    {
                        $recodeInfo[] = [
                            'info_type' => 3,
                            'pic' => $aliOss->getAuth($questionData['question_data']['photo1']),
                            'name' => $questionData['question_data']['name1'],
                        ];
                    }
                }

                if ($questionData['question_data']['recode2'])
                {
                    $recode2 = $questionData['question_data']['recode2'];
                    $recodeInfo[] = [
                        'info_type' => 1,
                        'pic' => $recode2['avatar'],
                        'name' => $questionData['question_data']['name2'],
                        'recode_name' => $recode2['name'],
                        'age' => $this->getAgeByBirth($recode2['year'], $recode2['month'], $recode2['day'], 2),
                    ];
                    $recodeInfo[] = [
                        'info_type' => 2,
                        'title' => '档案名称',
                        'des' => $recode2['name'],
                    ];
                    $recodeInfo[] = [
                        'info_type' => 2,
                        'title' => '性别',
                        'des' => $sexTxt[$recode2['type']] ?? '未知',
                    ];
                    $recodeInfo[] = [
                        'info_type' => 2,
                        'title' => '出生时间',
                        'des' => sprintf("%d-%02d-%02d %02d:%02d", $recode2['year'], $recode2['month'], $recode2['day'], $recode2['hour'], $recode2['minute']),
                    ];
                    $recodeInfo[] = [
                        'info_type' => 2,
                        'title' => '出生地点',
                        'des' => "{$recode2['birth_country']}{$recode2['birth_province']}{$recode2['birth_city']}",
                    ];
                    $recodeInfo[] = [
                        'info_type' => 2,
                        'title' => '现居地区',
                        'des' => "{$recode2['live_country']}{$recode2['live_province']}{$recode2['live_city']}",
                    ];
                    if ($questionData['question_data']['photo2'])
                    {
                        $recodeInfo[] = [
                            'info_type' => 3,
                            'pic' => $aliOss->getAuth($questionData['question_data']['photo2']),
                            'name' => '',
                        ];
                    }
                } else
                {
                    if ($questionData['question_data']['name2'])
                    {
                        $recodeInfo[] = [
                            'info_type' => 3,
                            'pic' => $aliOss->getAuth($questionData['question_data']['photo2']),
                            'name' => $questionData['question_data']['name2'],
                        ];
                    }
                }

                if ($recodeInfo)
                {
                    $resData[] = [
                        'type' => 3,
                        'title' => '档案',
                        'des' => in_array($goodInfo['info_type'], [1, 2, 3], true) ? '单人' : '双人',
                        'recode_info' => $recodeInfo
                    ];
                }
        }

        if ($questionData['supplement_info'])
        {
            // 旧样式
            // $supplementInfoDes = '';
            // foreach ($questionData['supplement_info'] as $item)
            // {
            //     $item['title'] = rtrim(rtrim($item['title'], '：'), ':') . '：';
            //
            //     $supplementInfoDes .= $item['title'];
            //     if ($item['type'] == 1)
            //     {   // 选择题
            //         if ($item['is_multi_choice'])
            //         {   // 多选
            //             foreach ($item['option'] as $item1)
            //             {
            //                 $supplementInfoDes .= $item1['title'] . '、';
            //             }
            //             $supplementInfoDes = rtrim($supplementInfoDes, '、');
            //         } else
            //         {   // 单选
            //             $supplementInfoDes .= $item['option']['title'];
            //         }
            //         $supplementInfoDes .= "\r\n";
            //     } else
            //     {   // 填空
            //         $supplementInfoDes .= "\r\n" . $item['content'] . "\r\n";
            //     }
            // }

            $supplementInfoDes = [];
            foreach ($questionData['supplement_info'] as $item)
            {
                $title = !strpos($item['title'], '：') && !strpos($item['title'], ':') ? $item['title'] . '：' : $item['title'];

                $content = '';
                if ($item['type'] == 1)
                {   // 选择题
                    if ($item['is_multi_choice'])
                    {   // 多选
                        foreach ($item['option'] as $item1)
                        {
                            $content .= $item1['title'] . '、';
                        }
                        $content = rtrim($content, '、');
                    } else
                    {   // 单选
                        $content .= $item['option']['title'];
                    }
                } else
                {   // 填空
                    $content = $item['content'];
                }

                $supplementInfoDes[] = [
                    'title' => $title,
                    'content' => $content
                ];
            }

            $resData[] = [
                'type' => 7,
                'title' => '补充问题',
                'des' => '',
                'data' => $supplementInfoDes
            ];
        } else
        {
            $resData[] = [
                'type' => 5,
                'title' => '补充问题',
                'des' => '无',
            ];
        }

        if ($isAdminOrAstr && isset($questionData['customer_supplement_info']) && $questionData['customer_supplement_info'])
        {
            $resData[] = [
                'type' => 8,
                'title' => '客服补充',
                'des' => $questionData['customer_supplement_info'],
            ];
        }

        return $resData;
    }

    /**
     * $date是时间戳
     * $type为1的时候是虚岁,2的时候是周岁
     * @param int $birthYear 出生的年 2022
     * @param int $birthMonth 出生的月   12
     * @param int $birthDay 出生的日  11
     * @param int $type
     * @return int
     */
    public function getAgeByBirth(int $birthYear, int $birthMonth, int $birthDay, $type = 1)
    {
        $nowYear = date("Y");
        $nowMonth = date("m");
        $nowDay = date("d");
        if ($type == 1)
        {
            $age = $nowYear - ($birthYear - 1);
        } else
        {
            if ($nowMonth < $birthMonth)
            {
                $age = $nowYear - $birthYear - 1;
            } elseif ($nowMonth == $birthMonth)
            {
                if ($nowDay < $birthDay)
                {
                    $age = $nowYear - $birthYear - 1;
                } else
                {
                    $age = $nowYear - $birthYear;
                }
            } else
            {
                $age = $nowYear - $birthYear;
            }
        }

        return $age;
    }
}
